package cn.kuick.match3.test5;

import java.util.ArrayList;
import java.util.List;


public class LongestAbsoluteFilePath {

	public static class TreeNode{
		public String name;
		public boolean isLeaf = false;
		public List<TreeNode> children = new ArrayList<TreeNode>();
	}
	
	public static String handle(String fs) {
		 TreeNode root = new TreeNode();
		 buildTree(root, 1, fs);
		 
		 StringBuffer longestPath = new StringBuffer();
		 StringBuffer tempPath = new StringBuffer();
		 
		 findLongestPath(root, tempPath, longestPath);
		 
		 String path = longestPath.toString();
		 
		 if (path.equals("")) {
			 return "0";
		 } else {
			 return longestPath.substring(1);
		 }
	}
	
	private static void findLongestPath(TreeNode root, StringBuffer path, StringBuffer longestPath) {
		int oldLen = path.length();
		
		path.append("/").append(root.name);
		
		if (root.isLeaf) {
			//System.out.println(path);
			longestPath(path, longestPath);
		} else {
			List<TreeNode> children = root.children;
			
			for(int i=0; i<children.size(); i++) {
				TreeNode child = children.get(i);
				findLongestPath(child, path, longestPath);
			}
		}
		
		path.setLength(oldLen);
	}

	private static void longestPath(StringBuffer path, StringBuffer longestPath) {
		if (path.length() > longestPath.length()) {
			longestPath.setLength(0);
			longestPath.append(path);
		}
	}

	private static TreeNode buildTree(TreeNode root, int j, String fs) {
		ArrayList<String> stack = new ArrayList<String>();
		
		StringBuffer name = new StringBuffer();
		StringBuffer seq = new StringBuffer();
		
		for(int i=0; i<fs.length(); i++) {
			char ch = fs.charAt(i);
			
			if(ch == '\n' && match(fs, i, j)) {
				if (name.length() > 0) {
					stack.add(name.toString());
					name.setLength(0);
				}
				
				i += j;
			} else {
				if (seq.length() > 0) {
					stack.add(seq.toString());
					seq.setLength(0);
				}
				
				name.append(ch);
			}
		}
		
		if (name.length() > 0) {
			stack.add(name.toString());
			name.setLength(0);
		}
		
		if (stack.size() > 0) {
			root.name = stack.get(0);
			
			for(int k=1; k<stack.size(); k++) {
				String path = stack.get(k);
				
				TreeNode child = new TreeNode();
				
				buildTree(child, j+1, path);
				
				if (child.name.indexOf(".") > 0) {
					child.isLeaf = true;
				}
				
				root.children.add(child);
			}
		}
		
		return root;
	}

	private static boolean match(String fs, int i, int j) {
		for(int k=0; k<j; k++) {
			if (fs.charAt(i + k + 1) != '\t') {
				return false;
			}
		}
		
		return fs.charAt(i + j + 1) != '\t';
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(handle("dir\n\tsubdir1\n\t\taaa.txt\n\t\tsubsubdir1\n\t\t\tbbb.txt\n\tsubdir2\n\t\tccc.txt\n\t\tdddddddddddddddddddddddd.txt"));
		System.out.println(handle("aaa\n\tccccccc.txt\n\tbbb\n\t\tdddd.txt"));
	}

}
